package com.xltt.vehicleControl.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.xltt.vehicleControl.R;
import com.xltt.vehicleControl.activity.AcSettingsActivity;
import com.xltt.vehicleControl.activity.LauncherActivity;
import com.xltt.vehicleControl.activity.LockSettingsActivity;
import com.xltt.vehicleControl.activity.LoginActivity;
import com.xltt.vehicleControl.activity.PowerSettingsActivity;
import com.xltt.vehicleControl.activity.WindowsSettingsActivity;
import com.xltt.vehicleControl.base.BaseFragment;
import com.xltt.vehicleControl.base.MyApplication;
import com.xltt.vehicleControl.bean.AdditionalVehicleStatus;
import com.xltt.vehicleControl.bean.BasicVehicleStatus;
import com.xltt.vehicleControl.bean.Capability;
import com.xltt.vehicleControl.bean.ClimateStatus;
import com.xltt.vehicleControl.bean.DrivingSafetyStatus;
import com.xltt.vehicleControl.bean.RemoteControlRequest;
import com.xltt.vehicleControl.bean.ServiceParameter;
import com.xltt.vehicleControl.bean.VehicleStatus;
import com.xltt.vehicleControl.util.Logger;
import com.xltt.vehicleControl.util.SharedPreferencesUtils;
import com.xltt.vehicleControl.util.ToastUtil;


import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class VehicleFunctionFragment extends BaseFragment implements LauncherActivity.VehicleCallBack{

    @BindView(R.id.base_layout)//背景
    RelativeLayout mBaseLayout;
    @BindView(R.id.seach_vehicle_btn)//寻车
    Button mSeachVehicleView;
    @BindView(R.id.ac_layout)//AC空调
    LinearLayout mAcView;
    @BindView(R.id.lock_layout)//车锁
    LinearLayout mLockView;
    @BindView(R.id.power_layout)//启动/点火
    LinearLayout mPowerView;
    @BindView(R.id.trunk_layout)//后备箱
    LinearLayout mTrunkView;
    @BindView(R.id.windows_layout)//车窗
    LinearLayout mWindowsView;

    @BindView(R.id.ac_txt)//AC空调
    TextView mAcTxt;
    @BindView(R.id.lock_txt)//车锁
    TextView mLockTxt;
    @BindView(R.id.power_txt)//启动/点火
    TextView mPowerTxt;
    @BindView(R.id.trunk_txt)//后备箱
    TextView mTrunkTxt;
    @BindView(R.id.windows_txt)//车窗
    TextView mWindowsTxt;

    public static final int AC_SETTINGS_RESULT_CODE = 1;
    public static final int LOCK_SETTINGS_RESULT_CODE = 2;
    public static final int WINDOWS_SETTINGS_RESULT_CODE = 3;
    public static final int POWER_SETTINGS_RESULT_CODE = 4;
    public static final int AC_CLOSE_RESULT_CODE = 5;
    public static final int WINDOWS_VENTILATION_RESULT_CODE = 6;
    public static final String COMMAND_PARAMETER = "command_parameter";
    public static final String AC_PARAMETER = "ac_parameter";
    public static final String TIME_PARAMETER = "time_parameter";//空调与发动机启动时长

    @Override
    public View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.vehicle_funtion_fragment, container, false);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(data == null){
            Logger.d("onActivityResult() data is null");
            return;
        }
        String acValue = data.getStringExtra(AC_PARAMETER);
        String timeValue = data.getStringExtra(TIME_PARAMETER);
        if(TextUtils.isEmpty(timeValue)){
            timeValue = "60";
        }
        String command = data.getStringExtra(COMMAND_PARAMETER);
        Logger.d("acValue = "+ acValue + ", command = " + command + ", timeValue = " + timeValue + ", resultCode = " + resultCode);
        View funtionView = getClickView(resultCode);
        RemoteControlRequest request = buildRemoteControl(funtionView,acValue, Integer.valueOf(timeValue),command);
        ((LauncherActivity)getActivity()).controlVehicleCommand(request);
        super.onActivityResult(requestCode, resultCode, data);
    }


    private View getClickView(int resultCode){
        if(resultCode == AC_SETTINGS_RESULT_CODE || resultCode == AC_CLOSE_RESULT_CODE){
            return mAcView;
        }else if(resultCode == LOCK_SETTINGS_RESULT_CODE){
            return mLockView;
        }else if(resultCode == WINDOWS_SETTINGS_RESULT_CODE || resultCode == WINDOWS_VENTILATION_RESULT_CODE){
            return mWindowsView;
        }else if(resultCode == POWER_SETTINGS_RESULT_CODE){
            return mPowerView;
        }
        return null;
    }

    @OnClick({R.id.seach_vehicle_btn,R.id.ac_layout,R.id.lock_layout,
            R.id.power_layout,R.id.trunk_layout,R.id.windows_layout})
    public void onViewClicked(View view) {
        //1.获取能力集是否支持，如果能力集为空需要重新登录
        LauncherActivity activity = ((LauncherActivity)getActivity());
        List<Capability> capability = activity.getCapabilityList();
        if(capability == null || capability.isEmpty()){
            Logger.d("get funtion list null,capability = " + capability);
            activity.doLogin(0);
            return;
        }

        //2.触发车控功能
        if(view == mAcView){
            boolean acSupport = Capability.isRemoteAirConditionSwitchEnabled(activity.getCapabilityList());
            if(acSupport){
                startActivityForResult(new Intent(mContext,AcSettingsActivity.class),0);
            }else{
                ToastUtil.show(getActivity(),getString(R.string.funtion_tip));
            }
        }else if(view == mLockView){
            startActivityForResult(new Intent(mContext, LockSettingsActivity.class),0);
        }else if(view == mWindowsView){
            startActivityForResult(new Intent(mContext, WindowsSettingsActivity.class),0);
        }else if(view == mPowerView){
            boolean powerSupport = Capability.isRemoteStartEngineEnabled(activity.getCapabilityList());
            if(powerSupport){
                startActivityForResult(new Intent(mContext, PowerSettingsActivity.class),0);
            }else{
                ToastUtil.show(getActivity(),getString(R.string.funtion_tip));
            }
        }else if(view == mTrunkView){
            //startActivityForResult(new Intent(mContext, TrunkSettingsActivity.class),0);
            ((LauncherActivity)getActivity()).controlVehicleCommand(buildRemoteControl(view,"0",60,""));
        }else if(view == mSeachVehicleView){
            boolean seachSupport = Capability.isHonkAndFlashEnabled(activity.getCapabilityList());
            if(seachSupport){
                activity.controlVehicleCommand(buildRemoteControl(view,"0",60,""));
            }else{
                ToastUtil.show(getActivity(),getString(R.string.funtion_tip));
            }
        }
    }

    /**
     * 构建车控请求参数
     * @param view
     * @return
     */
    private RemoteControlRequest buildRemoteControl(View view,String ac,int time,String command){
        ServiceParameter serviceParameter = null;
        RemoteControlRequest remoteControlRequest = null;
        if(view == mSeachVehicleView){
            serviceParameter = new ServiceParameter(ServiceParameter.PARAMETER_KEY.RHL, "horn-light-flash");
            remoteControlRequest = new RemoteControlRequest(RemoteControlRequest.SERVICE_ID_RHL);
            remoteControlRequest.setServiceParameters(serviceParameter);
        }else if(view == mAcView){
            serviceParameter = new ServiceParameter(ServiceParameter.PARAMETER_KEY.RCE, ac);
            remoteControlRequest = new RemoteControlRequest(RemoteControlRequest.SERVICE_ID_RCE);
            remoteControlRequest.setCommand(command);//空调开关参数指令
            if(command.equalsIgnoreCase("start")){
                remoteControlRequest.setServiceParameters(serviceParameter);
                remoteControlRequest.getOperationScheduling().setDuration(time * 6);
            }else{
                remoteControlRequest.getOperationScheduling().setDuration(60);//默认设置60等于空调打开10分钟
            }
        }else if(view == mLockView){
            if(command.equalsIgnoreCase("start")){
                remoteControlRequest = new RemoteControlRequest(RemoteControlRequest.SERVICE_ID_RDL);
            }else{
                remoteControlRequest = new RemoteControlRequest(RemoteControlRequest.SERVICE_ID_RDU);
            }
            remoteControlRequest.setCommand("start");
        }else if(view == mPowerView){
            remoteControlRequest = new RemoteControlRequest(RemoteControlRequest.SERVICE_ID_RES);
            remoteControlRequest.setCommand(command);
            if(command.equalsIgnoreCase("start")){
                remoteControlRequest.getOperationScheduling().setDuration(time * 6);
            }
        }else if(view == mTrunkView){
            remoteControlRequest = new RemoteControlRequest(RemoteControlRequest.SERVICE_ID_RTU);
        }else if(view == mWindowsView){
            if(command.equals(WindowsSettingsActivity.VENLATION_MODE)){//车窗透气标识
                command = "start";
                serviceParameter = new ServiceParameter(ServiceParameter.PARAMETER_KEY.RWS, ServiceParameter.PARAMETER_VALUE.VENTILATE);
            }else{
                serviceParameter = new ServiceParameter(ServiceParameter.PARAMETER_KEY.RWS, ServiceParameter.PARAMETER_VALUE.ALL);
            }
            remoteControlRequest = new RemoteControlRequest(RemoteControlRequest.SERVICE_ID_RWS);
            remoteControlRequest.setCommand(command);
            remoteControlRequest.setServiceParameters(serviceParameter);
        }
        String userId = SharedPreferencesUtils.getParam(getActivity(), LoginActivity.USERID,"").toString();
        remoteControlRequest.setUserId(userId);
        return remoteControlRequest;
    }

    @Override
    public void onResume() {
        super.onResume();
        LauncherActivity activity = ((LauncherActivity)getActivity());
        activity.registerObserver(this);
    }

    @Override
    public void onRefreshInfo(VehicleStatus vehicleStatus, String plateNo) {
        Logger.d("VehicleFunctionFragment revice observer");
        BasicVehicleStatus basicVehicleStatus = vehicleStatus.getBasicVehicleStatus();
        if(basicVehicleStatus == null){
            ToastUtil.show(getActivity(),"basicVehicleStatus data null");
            return;
        }
        AdditionalVehicleStatus mAdditionalVehicleStatus = vehicleStatus.getAdditionalVehicleStatus();
        if(getActivity() == null){
            Logger.d("exit app state, getActivity is null");
            return;
        }
        MyApplication application = ((MyApplication)getActivity().getApplication());
        if(application == null){//防止触发功能后立马退出app会出现该问题
            Logger.d("exit app state, application is null");
            return;
        }

        LauncherActivity activity = ((LauncherActivity)getActivity());
        List<Capability> capability = activity.getCapabilityList();

        //1、设置点火状态
        String enagineSwitch = basicVehicleStatus.getEngineStatus();//点火状态
        ClimateStatus mClimateStatus = mAdditionalVehicleStatus.getClimateStatus();
        application.setEngineStarted(enagineSwitch.equalsIgnoreCase("engine_running"));
        Drawable powerIcon = null;
        if(Capability.isRemoteStartEngineEnabled(capability)){
            powerIcon = enagineSwitch.equalsIgnoreCase("engine_running") ? getDrawable(R.mipmap.start_engine_icon2) : getDrawable(R.mipmap.start_engine_icon);
        }else{
            powerIcon = getDrawable(R.mipmap.start_engine_icon_disable);
        }
        mPowerTxt.setCompoundDrawables(null,powerIcon,null,null);

        //2.设置后备箱状态
        boolean trunkSwitch = mAdditionalVehicleStatus.getDrivingSafetyStatus().isTrunkNormal();//后备箱状态
//        Drawable trunkIcon = trunkSwitch ? getDrawable(R.mipmap.trunk_icon) : getDrawable(R.mipmap.trunk_icon2);
//        mTrunkTxt.setCompoundDrawables(null,trunkIcon,null,null);
        //3.设置车门锁状态
        //boolean doorSwitch = mAdditionalVehicleStatus.getDrivingSafetyStatus().isDoorAllCloseNormal();
        DrivingSafetyStatus mDrivingSafetyStatus = mAdditionalVehicleStatus.getDrivingSafetyStatus();
        boolean doorClose = mDrivingSafetyStatus.getDoorLockStatusDriverRear() == 1
                && mDrivingSafetyStatus.getDoorLockStatusDriver() == 1
                && mDrivingSafetyStatus.getDoorLockStatusPassenger() == 1
                && mDrivingSafetyStatus.getDoorLockStatusPassengerRear() == 1;
        Drawable doorIcon = doorClose ? getDrawable(R.mipmap.lock_icon) : getDrawable(R.mipmap.lock_icon2);
        mLockTxt.setCompoundDrawables(null,doorIcon,null,null);
        //4.设置空调状态
        boolean acOpen = mClimateStatus.getPreClimateActive();//空调状态 开-true 关-false
        Drawable acIcon = null;
        if(Capability.isRemoteAirConditionSwitchEnabled(capability)){
            acIcon = acOpen ? getDrawable(R.mipmap.ac_icon2) : getDrawable(R.mipmap.ac_icon);
            mBaseLayout.setBackgroundResource(R.mipmap.vehicle_control_backgound);
        }else{
            acIcon = getDrawable(R.mipmap.ac_icon_disable);
            mBaseLayout.setBackgroundResource(R.mipmap.vehicle_control_backgound3);
        }
        mAcTxt.setCompoundDrawables(null,acIcon,null,null);
        //5.车窗户状态
//        int windowsSwitch3 = mClimateStatus.isSunroofNormal();//天窗状态
//        boolean windowsSwitch2 = mClimateStatus.isVentilateStatus();//车窗透气
//        boolean windowsSwitch = mClimateStatus.isAllWinNormal();//所有车窗正常
        boolean window1 = mClimateStatus.getWinStatusDriver() == 2;//驾驶侧车窗位置状态
        boolean window2 = mClimateStatus.getWinStatusPassenger() == 2;//副驾驶侧车窗位置状态
        boolean window3 = mClimateStatus.getWinStatusDriverRear() == 2;//左后侧车窗位置状态
        boolean window4 = mClimateStatus.getWinStatusPassengerRear() == 2;//右后侧车窗位置状态
        boolean window5 = mClimateStatus.getSunroofOpenStatus() == 1;//天窗状态 0-未知 1-关闭 2打开
        boolean windowClose = window1 && window2 && window3 && window4 && window5;
        Drawable windowsIcon = windowClose ? getDrawable(R.mipmap.door_icon) : getDrawable(R.mipmap.door_icon2);
        mWindowsTxt.setCompoundDrawables(null,windowsIcon,null,null);
        //6.寻车状态
        if(Capability.isHonkAndFlashEnabled(capability)){
            mSeachVehicleView.setBackgroundResource(R.mipmap.seach_car_icon);
        }else{
            mSeachVehicleView.setBackgroundResource(R.mipmap.seach_car_icon2);
        }

        //7.刷新button点击状态
        onRemoteControl(COMPLETE);
        Logger.d("MyApplication 车辆引擎 = " + enagineSwitch + "，后备箱关闭 = " + trunkSwitch + ",车门锁关闭 = " + doorClose + ",空调打开 = " + acOpen + ",车窗（天窗、车窗透气、四车门）关闭 = " + windowClose);
    }


    @Override
    public void onRemoteControl(int result) {
        Logger.d("接收车控指令结果 , result = " + result);
        if(mBaseLayout == null){
            Logger.d("mBaseLayout is null");
            return;
        }
        LauncherActivity activity = ((LauncherActivity)getActivity());
        List<Capability> capability = activity.getCapabilityList();
        boolean acSupport = Capability.isRemoteAirConditionSwitchEnabled(capability);
        if(acSupport){
            mBaseLayout.setBackgroundResource(result == COMPLETE ? R.mipmap.vehicle_control_backgound : R.mipmap.vehicle_control_backgound2);
        }else{
            mBaseLayout.setBackgroundResource(result == COMPLETE ? R.mipmap.vehicle_control_backgound3 : R.mipmap.vehicle_control_backgound2);
        }
        mSeachVehicleView.setBackgroundResource(result == COMPLETE ? R.mipmap.seach_car_icon : R.mipmap.seach_car_icon2);
        mSeachVehicleView.setEnabled(result == COMPLETE);
        mAcView.setEnabled(result == COMPLETE);
        mLockView.setEnabled(result == COMPLETE);
        mPowerView.setEnabled(result == COMPLETE);
        mTrunkView.setEnabled(result == COMPLETE);
        mWindowsView.setEnabled(result == COMPLETE);
    }

    @Override
    public void onFunctionList(List<Capability> capabilityList) {
        Logger.d("更新车控功能图标");
        if(mBaseLayout == null){
            Logger.d("mBaseLayout is null");
            return;
        }
        boolean acSupport = Capability.isRemoteAirConditionSwitchEnabled(capabilityList);
        boolean powerSupport = Capability.isRemoteStartEngineEnabled(capabilityList);
        boolean seachSupport = Capability.isHonkAndFlashEnabled(capabilityList);
        mAcView.setEnabled(acSupport);
        mPowerView.setEnabled(powerSupport);
        mSeachVehicleView.setEnabled(seachSupport);
        if(!acSupport){
            mAcTxt.setCompoundDrawables(null,getDrawable(R.mipmap.ac_icon_disable),null,null);
            mAcTxt.setTextColor(Color.GRAY);
            mBaseLayout.setBackgroundResource(R.mipmap.vehicle_control_backgound3);
        }
        if(!powerSupport){
            mPowerTxt.setCompoundDrawables(null,getDrawable(R.mipmap.start_engine_icon_disable),null,null);
            mPowerTxt.setTextColor(Color.GRAY);
        }
        if(!seachSupport){
            mSeachVehicleView.setBackgroundResource(R.mipmap.seach_car_icon2);
            mSeachVehicleView.setTextColor(Color.GRAY);
        }
    }

    private Drawable getDrawable(int resouceId){
        Drawable drawable = getActivity().getResources().getDrawable(resouceId);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                drawable.getMinimumHeight());
        return drawable;
    }
}
